package org.xs.big_event.service.impl;

import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.xs.big_event.service.IFileUpLoadService;
import org.xs.big_event.utils.AilOssUtil;
import org.xs.big_event.utils.R;
import org.xs.big_event.utils.ResponseEnum;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
//@PropertySource("classpath:.properties")
public class FileUpLoadService implements IFileUpLoadService {
    @Autowired
    AilOssUtil ossUtil;
    //文件上传
    /*
    * @Description: 文件上传
    * @Param: [file]
    * @return: R
    * 1.把文件内容上传到磁盘上
    * 2.返回上传文件的访问路径
    * 3.返回上传
     */
    @Override
    public R upload(MultipartFile file) {
        //判断文件是否为空
        if (file.isEmpty()) {
            return R.error(ResponseEnum.FILE_EMPTY);
        }
        //1.把文件内容上传到磁盘上
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //保证文件名唯一
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //创建文件
        //2.返回上传文件的访问路径
        //String url = "http://localhost:8080/file/" + fileName;
        String url;
        try {
            url= ossUtil.upLoadFile(fileName, file.getInputStream());
        } catch (ClientException | IOException e) {
            return R.error(ResponseEnum.FILE_UPLOAD_ERROR);
        }
        return R.ok(url);
    }
}
